package solution.array;

public class ArrayTest {
    public static void main(String[] args) {
        int arr[][] = new int[6][6];
        arr[0][0] = 1;
        arr[1][1] = 2;

        //二位数组行数
        int rows = arr.length;
        //二位数组列数
        int columns = 0;
        for (int[] ints : arr) {
            columns = ints.length;
            break;
        }

        //有效元素个数 , 有效元素+1实际上就是稀疏数组的行数，
        int sum = 0;
        //遍历二位数组
        for (int i = 0; i < rows; i++) {
            for (int j = 0 ; j < columns ; j++){
                if (arr[i][j] != 0){
                  sum++;
                }
            }
        }
        int sparseArray[][] = new int[sum+1][3];
        sparseArray[0][0] = rows; //记录原始数组行数
        sparseArray[0][1] = columns; //记录原始数组列数
        sparseArray[0][2] = sum; //记录有效值个数
        int count = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0 ; j < columns ; j++){
                if (arr[i][j] != 0){
                    count++;
                    sparseArray[count][0] = i; //所在行
                    sparseArray[count][1] = j; //所在列
                    sparseArray[count][2] = arr[i][j]; //值
                }
            }
        }

        for (int i = 0; i < sparseArray.length; i++) {
            System.out.printf("%d\t%d\t%d\t\n",sparseArray[i][0],sparseArray[i][1],sparseArray[i][2]);
        }

        /**
         * 稀疏数组转二位数组
         */
        int newArrayRow = sparseArray[0][0];
        int newArrayColumn = sparseArray[0][1];
        int newArraySum = sparseArray[0][2];
        int newArray[][] = new int[newArrayRow][newArrayColumn];

        // i = 1 , 因为第一行数纪录原始数组的行列和有效值
        for (int i = 1 ; i < sparseArray.length ; i++){
            newArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
        }
        System.out.println("恢复后");
        for (int[] ints : newArray) {
            for (int anInt : ints) {
                System.out.println(anInt);
            }
        }
    }
}
